package com.hmall.order.Interceptor;


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取 authorization 信息
        String authorization = request.getHeader("authorization");
        if (authorization != null) {
            // 将 userId 保存到 ThreadLocal 中
            UserContext.setUserId(authorization);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除 ThreadLocal 中的数据，防止内存泄漏
        UserContext.clear();
    }
}